package net.shopxx.action.shop;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;

import net.sf.json.JSONArray;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.shopxx.bean.CartItemCookie;
import net.shopxx.bean.Pager;
import net.shopxx.bean.SystemConfig;
import net.shopxx.common.JCaptchaEngine;
import net.shopxx.entity.CartItem;
import net.shopxx.entity.CartItemGroupbuy;
import net.shopxx.entity.CartItemProduct;
import net.shopxx.entity.Groupbuy;
import net.shopxx.entity.Member;
import net.shopxx.entity.Product;
import net.shopxx.entity.ProductComment;
import net.shopxx.entity.ProductConsult;
import net.shopxx.entity.Productitem;
import net.shopxx.service.AgreementService;
import net.shopxx.service.CartItemService;
import net.shopxx.service.GroupbuyService;
import net.shopxx.service.MailService;
import net.shopxx.service.MemberRankService;
import net.shopxx.service.MemberService;
import net.shopxx.service.ProductCommentService;
import net.shopxx.service.ProductConsultService;
import net.shopxx.service.ProductService;
import net.shopxx.service.ProductitemService;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.octo.captcha.service.CaptchaService;
import com.opensymphony.oscache.util.StringUtil;
import com.opensymphony.xwork2.interceptor.annotations.InputConfig;
import com.opensymphony.xwork2.validator.annotations.EmailValidator;
import com.opensymphony.xwork2.validator.annotations.RegexFieldValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.StringLengthFieldValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;

/**
 * 前台Action类 - 会员
 */

@ParentPackage("shop")
@Results( {
		@Result(name = "memberCenterIndexAction", location = "member_center!index.action", type = "redirect"),
		@Result(name = "index", location = "/", type = "redirect") })
public class MemberAction extends BaseShopAction {

	private static final long serialVersionUID = 1115660086350733102L;

	private Member member;
	private ProductConsult consult;
	private Boolean isAgreeAgreement;
	private String passwordRecoverKey;

	@Resource
	private MemberService memberService;
	@Resource
	private MemberRankService memberRankService;
	@Resource
	private AgreementService agreementService;
	@Resource
	private CaptchaService captchaService;
	@Resource
	private MailService mailService;
	@Resource
	private ProductService productService;
	@Resource
	private GroupbuyService groupbuyService;
	@Resource
	private CartItemService cartItemService;
	@Resource
	private ProductConsultService productConsultService;
	@Resource
	private ProductCommentService productCommentService;
	@Resource
	private ProductitemService productitemService;

	// 会员登录验证
	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "member.username", message = "用户名不允许为空!"),
			@RequiredStringValidator(fieldName = "member.password", message = "密码不允许为空!") })
	@InputConfig(resultName = "error")
	@SuppressWarnings("unchecked")
	public String login() throws Exception {
		String captchaID = getRequest().getSession().getId();
		String challengeResponse = StringUtils.upperCase(getRequest()
				.getParameter(JCaptchaEngine.CAPTCHA_INPUT_NAME));
		if (StringUtils.isEmpty(challengeResponse)
				|| captchaService.validateResponseForID(captchaID,
						challengeResponse) == false) {
			addActionError("验证码输入错误!");
			return ERROR;
		}
		SystemConfig systemConfig = getSystemConfig();
		Member loginMember = memberService.getMemberByUsername(member
				.getUsername());
		if (loginMember != null) {
			// 解除会员账户锁定
			if (loginMember.getIsAccountLocked()) {
				if (systemConfig.getIsLoginFailureLock()) {
					int loginFailureLockTime = systemConfig
							.getLoginFailureLockTime();
					if (loginFailureLockTime != 0) {
						Date lockedDate = loginMember.getLockedDate();
						Date nonLockedTime = DateUtils.addMinutes(lockedDate,
								loginFailureLockTime);
						Date now = new Date();
						if (now.after(nonLockedTime)) {
							loginMember.setLoginFailureCount(0);
							loginMember.setIsAccountLocked(false);
							loginMember.setLockedDate(null);
							memberService.update(loginMember);
						}
					}
				} else {
					loginMember.setLoginFailureCount(0);
					loginMember.setIsAccountLocked(false);
					loginMember.setLockedDate(null);
					memberService.update(loginMember);
				}
			}
			if (!loginMember.getIsAccountEnabled()) {
				addActionError("您的账号已被禁用,无法登录!");
				return ERROR;
			}
			if (loginMember.getIsAccountLocked()) {
				addActionError("您的账号已被锁定,无法登录!");
				return ERROR;
			}
			if (!memberService.verifyMember(member.getUsername(), member
					.getPassword())) {
				if (systemConfig.getIsLoginFailureLock()) {
					int loginFailureLockCount = getSystemConfig()
							.getLoginFailureLockCount();
					int loginFailureCount = loginMember.getLoginFailureCount() + 1;
					if (loginFailureCount >= systemConfig
							.getLoginFailureLockCount()) {
						loginMember.setIsAccountLocked(true);
						loginMember.setLockedDate(new Date());
					}
					loginMember.setLoginFailureCount(loginFailureCount);
					memberService.update(loginMember);
					if (getSystemConfig().getIsLoginFailureLock()
							&& loginFailureLockCount - loginFailureCount <= 3) {
						addActionError("若连续" + loginFailureLockCount
								+ "次密码输入错误,您的账号将被锁定!");
					} else {
						addActionError("您的用户名或密码错误!");
					}
				} else {
					addActionError("用户名或密码错误!");
				}
				return ERROR;
			}
		} else {
			addActionError("用户名或密码错误!");
			return ERROR;
		}
		loginMember.setLoginIp(getRequest().getRemoteAddr());
		loginMember.setLoginDate(new Date());
		memberService.update(loginMember);

		// 写入会员登录Session
		setSession(Member.LOGIN_MEMBER_ID_SESSION_NAME, loginMember.getId());
		// 登陆的会员写入session
		// setSession(Member.LOGIN_MEMBER_SESSION_NAME, loginMember);
		// 写入会员登录Cookie
		Cookie loginMemberUsernameCookie = new Cookie(
				Member.LOGIN_MEMBER_USERNAME_COOKIE_NAME, URLEncoder.encode(
						member.getUsername().toLowerCase(), "UTF-8"));
		loginMemberUsernameCookie.setPath(getRequest().getContextPath() + "/");
		getResponse().addCookie(loginMemberUsernameCookie);

		// 合并购物车
		Cookie[] cookies = getRequest().getCookies();
		if (cookies != null && cookies.length > 0) {
			for (Cookie cookie : cookies) {
				if (StringUtils.equalsIgnoreCase(cookie.getName(),
						CartItemCookie.CART_ITEM_LIST_COOKIE_NAME)) {
					if (StringUtils.isNotEmpty(cookie.getValue())) {
						JsonConfig jsonConfig = new JsonConfig();
						jsonConfig.setRootClass(CartItemCookie.class);
						JSONArray jsonArray = JSONArray.fromObject(cookie
								.getValue());
						List<CartItemCookie> cartItemCookieList = (List<CartItemCookie>) JSONSerializer
								.toJava(jsonArray, jsonConfig);
						for (CartItemCookie cartItemCookie : cartItemCookieList) {
							if(cartItemCookie.getT().equalsIgnoreCase(CartItem.TYPE_PRODUCT))
							{
								Productitem productItem = productitemService.load(cartItemCookie.getI());
//								Product product = productService.load(cartItemCookie.getI());
								if (productItem != null) {
									CartItemProduct cartItem = new CartItemProduct();
									cartItem.setMember(loginMember);
									cartItem.setProductitem(productItem);
									cartItem.setQuantity(cartItemCookie.getQ());
									cartItemService.save(cartItem);
								}
							}
							else if(cartItemCookie.getT().equalsIgnoreCase(CartItem.TYPE_GROUPBUY))
							{
								Groupbuy groupbuy = groupbuyService.load(cartItemCookie.getI());
								if (groupbuy != null) {
									CartItemGroupbuy cartItem = new CartItemGroupbuy();
									cartItem.setMember(loginMember);
									cartItem.setGroupbuy(groupbuy);
									cartItem.setQuantity(cartItemCookie.getQ());
									cartItemService.save(cartItem);
								}
							}
						}
					}
				}
			}
		}

		// 清空临时购物车Cookie
		Cookie cartItemCookie = new Cookie(
				CartItemCookie.CART_ITEM_LIST_COOKIE_NAME, null);
		cartItemCookie.setPath(getRequest().getContextPath() + "/");
		cartItemCookie.setMaxAge(0);
		getResponse().addCookie(cartItemCookie);

		String redirectionUrl = (String) getSession(Member.LOGIN_REDIRECTION_URL_SESSION_NAME);
		getRequest().getSession().removeAttribute(
				Member.LOGIN_REDIRECTION_URL_SESSION_NAME);
		if (StringUtils.isEmpty(redirectionUrl)) {
			return "memberCenterIndexAction";
		} else {
			getResponse().sendRedirect(redirectionUrl);
			return null;
		}
	}

	// Ajax会员登录验证
	@SuppressWarnings("unchecked")
	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "member.username", message = "用户名不允许为空!"),
			@RequiredStringValidator(fieldName = "member.password", message = "密码不允许为空!") })
	@InputConfig(resultName = "error")
	public String ajaxLogin() throws Exception {
		String captchaID = getRequest().getSession().getId();
		String challengeResponse = StringUtils.upperCase(getRequest()
				.getParameter(JCaptchaEngine.CAPTCHA_INPUT_NAME));
		if (StringUtils.isEmpty(challengeResponse)
				|| captchaService.validateResponseForID(captchaID,
						challengeResponse) == false) {
			return ajaxJsonErrorMessage("验证码输入错误！");
		}
		SystemConfig systemConfig = getSystemConfig();
		Member loginMember = memberService.getMemberByUsername(member
				.getUsername());
		if (loginMember != null) {
			// 解除会员账户锁定
			if (loginMember.getIsAccountLocked()) {
				if (systemConfig.getIsLoginFailureLock()) {
					int loginFailureLockTime = systemConfig
							.getLoginFailureLockTime();
					if (loginFailureLockTime != 0) {
						Date lockedDate = loginMember.getLockedDate();
						Date nonLockedTime = DateUtils.addMinutes(lockedDate,
								loginFailureLockTime);
						Date now = new Date();
						if (now.after(nonLockedTime)) {
							loginMember.setLoginFailureCount(0);
							loginMember.setIsAccountLocked(false);
							loginMember.setLockedDate(null);
							memberService.update(loginMember);
						}
					}
				} else {
					loginMember.setLoginFailureCount(0);
					loginMember.setIsAccountLocked(false);
					loginMember.setLockedDate(null);
					memberService.update(loginMember);
				}
			}
			if (!loginMember.getIsAccountEnabled()) {
				return ajaxJsonErrorMessage("您的账号已被禁用,无法登录！");
			}
			if (loginMember.getIsAccountLocked()) {
				return ajaxJsonErrorMessage("您的账号已被锁定,无法登录！");
			}
			if (!memberService.verifyMember(member.getUsername(), member
					.getPassword())) {
				if (systemConfig.getIsLoginFailureLock()) {
					int loginFailureLockCount = getSystemConfig()
							.getLoginFailureLockCount();
					int loginFailureCount = loginMember.getLoginFailureCount() + 1;
					if (loginFailureCount >= systemConfig
							.getLoginFailureLockCount()) {
						loginMember.setIsAccountLocked(true);
						loginMember.setLockedDate(new Date());
					}
					loginMember.setLoginFailureCount(loginFailureCount);
					memberService.update(loginMember);
					if (loginFailureLockCount - loginFailureCount <= 3) {
						return ajaxJsonErrorMessage("若连续"
								+ loginFailureLockCount + "次密码输入错误,您的账号将被锁定！");
					} else {
						return ajaxJsonErrorMessage("您的用户名或密码错误！");
					}
				} else {
					return ajaxJsonErrorMessage("您的用户名或密码错误！");
				}
			}
		} else {
			return ajaxJsonErrorMessage("您的用户名或密码错误！");
		}
		loginMember.setLoginIp(getRequest().getRemoteAddr());
		loginMember.setLoginDate(new Date());
		memberService.update(loginMember);

		// 写入会员登录Session
		setSession(Member.LOGIN_MEMBER_ID_SESSION_NAME, loginMember.getId());

		// 写入会员登录Cookie
		Cookie loginMemberUsernameCookie = new Cookie(
				Member.LOGIN_MEMBER_USERNAME_COOKIE_NAME, URLEncoder.encode(
						member.getUsername().toLowerCase(), "UTF-8"));
		loginMemberUsernameCookie.setPath(getRequest().getContextPath() + "/");
		getResponse().addCookie(loginMemberUsernameCookie);

		// 合并购物车
		Cookie[] cookies = getRequest().getCookies();
		if (cookies != null && cookies.length > 0) {
			for (Cookie cookie : cookies) {
				if (StringUtils.equalsIgnoreCase(cookie.getName(),
						CartItemCookie.CART_ITEM_LIST_COOKIE_NAME)) {
					if (StringUtils.isNotEmpty(cookie.getValue())) {
						JsonConfig jsonConfig = new JsonConfig();
						jsonConfig.setRootClass(CartItemCookie.class);
						JSONArray jsonArray = JSONArray.fromObject(cookie
								.getValue());
						List<CartItemCookie> cartItemCookieList = (List<CartItemCookie>) JSONSerializer
								.toJava(jsonArray, jsonConfig);
						for (CartItemCookie cartItemCookie : cartItemCookieList) {
							if(cartItemCookie.getT().equalsIgnoreCase(CartItem.TYPE_PRODUCT))
							{
								//判断是否存在
//								Product product = productService.load(cartItemCookie.getI());
								Productitem productItem = productitemService.load(cartItemCookie.getI());
								if (productItem != null) {
									Pager pager = new Pager();
									pager.setPageSize(Integer.MAX_VALUE);
									DetachedCriteria detachedCriteria = DetachedCriteria.forClass(CartItem.class);
									detachedCriteria.add(Restrictions.eq("member.id", loginMember.getId()));
									detachedCriteria.add(Restrictions.eq("productitem.id", cartItemCookie.getI()));
									pager = cartItemService.findByPager(pager, detachedCriteria);
									List<CartItemProduct> existedCartItem = pager.getList();
									
									if(existedCartItem!=null && !existedCartItem.isEmpty())
									{
										CartItemProduct cartItem = existedCartItem.get(0);
										cartItem.setQuantity(cartItem.getQuantity()+cartItemCookie.getQ());
										cartItemService.update(cartItem);
									}
									else
									{
										CartItemProduct cartItem = new CartItemProduct();
										cartItem.setMember(loginMember);
										cartItem.setProductitem(productItem);
										cartItem.setQuantity(cartItemCookie.getQ());
										cartItemService.save(cartItem);
									}
								}
							}
							else if(cartItemCookie.getT().equalsIgnoreCase(CartItem.TYPE_GROUPBUY))
							{
								Groupbuy groupbuy = groupbuyService.load(cartItemCookie.getI());
								if (groupbuy != null) {
									
									Pager pager = new Pager();
									pager.setPageSize(Integer.MAX_VALUE);
									DetachedCriteria detachedCriteria = DetachedCriteria.forClass(CartItem.class);
									detachedCriteria.add(Restrictions.eq("member.id", loginMember.getId()));
									detachedCriteria.add(Restrictions.eq("groupbuy.id", cartItemCookie.getI()));
									pager = cartItemService.findByPager(pager, detachedCriteria);
									List<CartItemGroupbuy> existedCartItem = pager.getList();
									
									if(existedCartItem!=null && !existedCartItem.isEmpty())
									{
										CartItemGroupbuy cartItem = existedCartItem.get(0);
										cartItem.setQuantity(cartItem.getQuantity()+cartItemCookie.getQ());
										cartItemService.update(cartItem);
									}
									else
									{
										CartItemGroupbuy cartItem = new CartItemGroupbuy();
										cartItem.setMember(loginMember);
										cartItem.setGroupbuy(groupbuy);
										cartItem.setQuantity(cartItemCookie.getQ());
										cartItemService.save(cartItem);
									}
								}
							}
							
						}
					}
				}
			}
		}

		// 清空临时购物车Cookie
		Cookie cartItemCookie = new Cookie(
				CartItemCookie.CART_ITEM_LIST_COOKIE_NAME, null);
		cartItemCookie.setPath(getRequest().getContextPath() + "/");
		cartItemCookie.setMaxAge(0);
		getResponse().addCookie(cartItemCookie);

		return ajaxJsonSuccessMessage("会员登录成功！");
	}

	// 会员注销
	public String logout() {
		getRequest().getSession().removeAttribute(
				Member.LOGIN_MEMBER_ID_SESSION_NAME);
		Cookie cookie = new Cookie(Member.LOGIN_MEMBER_USERNAME_COOKIE_NAME,
				null);
		cookie.setPath(getRequest().getContextPath() + "/");
		cookie.setMaxAge(0);
		getResponse().addCookie(cookie);
		return "index";
	}

	// 获取注册协议内容
	public String getAgreement() {
		return ajaxText(agreementService.getAgreement().getContent());
	}

	// 检查用户名是否存在
	public String checkUsername() {
		String username = member.getUsername();
		if (memberService.isExistByUsername(username)) {
			return ajaxText("false");
		} else {
			return ajaxText("true");
		}
	}

	// Ajax会员注册保存
	@SuppressWarnings("unchecked")
	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "member.username", message = "用户名不允许为空!"),
			@RequiredStringValidator(fieldName = "member.password", message = "密码不允许为空!"),
			@RequiredStringValidator(fieldName = "member.email", message = "E-mail不允许为空!") }, stringLengthFields = {
			@StringLengthFieldValidator(fieldName = "member.username", minLength = "2", maxLength = "20", message = "用户名长度必须在${minLength}到${maxLength}之间!"),
			@StringLengthFieldValidator(fieldName = "member.password", minLength = "4", maxLength = "20", message = "密码长度必须在${minLength}到${maxLength}之间!") }, emails = { @EmailValidator(fieldName = "member.email", message = "E-mail格式错误!") }, regexFields = { @RegexFieldValidator(fieldName = "member.username", expression = "^[0-9a-z_A-Z\u4e00-\u9fa5]+$", message = "用户名只允许包含中文、英文、数字和下划线!") })
	@InputConfig(resultName = "error")
	public String ajaxRegister() throws Exception {
		if (isAgreeAgreement == null || isAgreeAgreement == false) {
			return ajaxJsonErrorMessage("必须同意注册协议才可进行注册操作！");
		}
		if (!getSystemConfig().getIsRegister()) {
			return ajaxJsonErrorMessage("本站注册功能现已关闭！");
		}
		String captchaID = getRequest().getSession().getId();
		String challengeResponse = StringUtils.upperCase(getRequest()
				.getParameter(JCaptchaEngine.CAPTCHA_INPUT_NAME));
		if (StringUtils.isEmpty(challengeResponse)
				|| captchaService.validateResponseForID(captchaID,
						challengeResponse) == false) {
			return ajaxJsonErrorMessage("验证码输入错误！");
		}
		member.setUsername(member.getUsername().toLowerCase());
		member.setPassword(DigestUtils.md5Hex(member.getPassword()));
		member.setSafeQuestion(null);
		member.setSafeAnswer(null);
		member.setMemberRank(memberRankService.getDefaultMemberRank());
		member.setPoint(0);
		member.setDeposit(new BigDecimal("0"));
		member.setIsAccountEnabled(true);
		member.setIsAccountLocked(false);
		member.setLoginFailureCount(0);
		member.setPasswordRecoverKey(null);
		member.setLockedDate(null);
		member.setLoginDate(new Date());
		member.setRegisterIp(getRequest().getRemoteAddr());
		member.setLoginIp(getRequest().getRemoteAddr());
		member.setMemberAttributeMap(null);
		member.setReceiverSet(null);
		member.setFavoriteProductSet(null);
		memberService.save(member);

		// 写入会员登录Session
		setSession(Member.LOGIN_MEMBER_ID_SESSION_NAME, member.getId());

		// 写入会员登录Cookie
		Cookie loginMemberCookie = new Cookie(
				Member.LOGIN_MEMBER_USERNAME_COOKIE_NAME, URLEncoder.encode(
						member.getUsername().toLowerCase(), "UTF-8"));
		loginMemberCookie.setPath(getRequest().getContextPath() + "/");
		getResponse().addCookie(loginMemberCookie);

		// 合并购物车
		Cookie[] cookies = getRequest().getCookies();
		if (cookies != null && cookies.length > 0) {
			for (Cookie cookie : cookies) {
				if (StringUtils.equalsIgnoreCase(cookie.getName(),
						CartItemCookie.CART_ITEM_LIST_COOKIE_NAME)) {
					if (StringUtils.isNotEmpty(cookie.getValue())) {
						JsonConfig jsonConfig = new JsonConfig();
						jsonConfig.setRootClass(CartItemCookie.class);
						JSONArray jsonArray = JSONArray.fromObject(cookie
								.getValue());
						List<CartItemCookie> cartItemCookieList = (List<CartItemCookie>) JSONSerializer
								.toJava(jsonArray, jsonConfig);
						for (CartItemCookie cartItemCookie : cartItemCookieList) {
							if(cartItemCookie.getT().equalsIgnoreCase(CartItem.TYPE_PRODUCT))
							{
//								Product product = productService.load(cartItemCookie.getI());
								Productitem productItem = productitemService.load(cartItemCookie.getI());
								if (productItem != null) {
									CartItemProduct cartItem = new CartItemProduct();
									cartItem.setMember(member);
									cartItem.setProductitem(productItem);
									cartItem.setQuantity(cartItemCookie.getQ());
									cartItemService.save(cartItem);
								}
							}
							else if(cartItemCookie.getT().equalsIgnoreCase(CartItem.TYPE_GROUPBUY))
							{
								Groupbuy groupbuy = groupbuyService.load(cartItemCookie.getI());
								if (groupbuy != null) {
									CartItemGroupbuy cartItem = new CartItemGroupbuy();
									cartItem.setMember(member);
									cartItem.setGroupbuy(groupbuy);
									cartItem.setQuantity(cartItemCookie.getQ());
									cartItemService.save(cartItem);
								}
							}
						}
					}
				}
			}
		}

		// 清空临时购物车Cookie
		Cookie cartItemCookie = new Cookie(
				CartItemCookie.CART_ITEM_LIST_COOKIE_NAME, null);
		cartItemCookie.setPath(getRequest().getContextPath() + "/");
		cartItemCookie.setMaxAge(0);
		getResponse().addCookie(cartItemCookie);

		return ajaxJsonSuccessMessage("会员注册成功！");
	}

	// 密码找回
	public String passwordRecover() throws Exception {
		return "password_recover";
	}

	// 发送密码找回邮件
	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "member.username", message = "用户名不允许为空!"),
			@RequiredStringValidator(fieldName = "member.email", message = "E-mail不允许为空!") }, emails = { @EmailValidator(fieldName = "member.email", message = "E-mail格式错误!") })
	@InputConfig(resultName = "error")
	public String sendPasswordRecoverMail() throws Exception {
		Member persistent = memberService.getMemberByUsername(member
				.getUsername());
		if (persistent == null
				|| StringUtils.equalsIgnoreCase(persistent.getEmail(), member
						.getEmail()) == false) {
			return ajaxJsonErrorMessage("用户名或E-mail输入错误！");
		}
		if (StringUtils.isNotEmpty(persistent.getSafeQuestion())
				&& StringUtils.isNotEmpty(persistent.getSafeAnswer())) {
			if (StringUtils.isEmpty(member.getSafeAnswer())) {
				Map<String, String> jsonMap = new HashMap<String, String>();
				jsonMap.put("safeQuestion", persistent.getSafeQuestion());
				jsonMap.put(STATUS, WARN);
				jsonMap.put(MESSAGE, "请填写密码保护问题答案！");
				return ajaxJson(jsonMap);
			}
			if (StringUtils.equalsIgnoreCase(persistent.getSafeAnswer(), member
					.getSafeAnswer()) == false) {
				return ajaxJsonErrorMessage("密码保护答案错误！");
			}
		}
		if (!mailService.isMailConfigComplete()) {
			return ajaxJsonErrorMessage("系统邮件发送功能尚未配置，请联系管理员！");
		}
		persistent.setPasswordRecoverKey(memberService
				.buildPasswordRecoverKey());
		memberService.update(persistent);
		mailService.sendPasswordRecoverMail(persistent);
		return ajaxJsonSuccessMessage("系统已发送邮件到您的E-mail，请根据邮件提示操作！");
	}

	// 密码修改
	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "id", message = "ID不允许为空!"),
			@RequiredStringValidator(fieldName = "passwordRecoverKey", message = "passwordRecoverKey不允许为空!") })
	@InputConfig(resultName = "error")
	public String passwordModify() throws Exception {
		Member persistent = memberService.get(id);
		if (persistent == null
				|| StringUtils.equalsIgnoreCase(persistent
						.getPasswordRecoverKey(), passwordRecoverKey) == false) {
			addActionError("对不起，此密码找回链接已失效！");
			return ERROR;
		}
		Date passwordRecoverKeyBuildDate = memberService
				.getPasswordRecoverKeyBuildDate(passwordRecoverKey);
		Date passwordRecoverKeyExpiredDate = DateUtils
				.addMinutes(passwordRecoverKeyBuildDate,
						Member.PASSWORD_RECOVER_KEY_PERIOD);
		Date now = new Date();
		if (now.after(passwordRecoverKeyExpiredDate)) {
			addActionError("对不起，此密码找回链接已过期！");
			return ERROR;
		}
		return "password_modify";
	}

	// 密码更新
	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "id", message = "ID不允许为空!"),
			@RequiredStringValidator(fieldName = "passwordRecoverKey", message = "passwordRecoverKey不允许为空!"),
			@RequiredStringValidator(fieldName = "member.password", message = "密码不允许为空!") }, stringLengthFields = { @StringLengthFieldValidator(fieldName = "member.password", minLength = "4", maxLength = "20", message = "密码长度必须在${minLength}到${maxLength}之间!") })
	@InputConfig(resultName = "error")
	public String passwordUpdate() throws Exception {
		Member persistent = memberService.get(id);
		if (persistent == null
				|| StringUtils.equalsIgnoreCase(persistent
						.getPasswordRecoverKey(), passwordRecoverKey) == false) {
			addActionError("对不起，此密码找回链接已失效！");
			return ERROR;
		}
		Date passwordRecoverKeyBuildDate = memberService
				.getPasswordRecoverKeyBuildDate(passwordRecoverKey);
		Date passwordRecoverKeyExpiredDate = DateUtils
				.addMinutes(passwordRecoverKeyBuildDate,
						Member.PASSWORD_RECOVER_KEY_PERIOD);
		Date now = new Date();
		if (now.after(passwordRecoverKeyExpiredDate)) {
			addActionError("对不起，此密码找回链接已过期！");
			return ERROR;
		}
		persistent.setPassword(DigestUtils.md5Hex(member.getPassword()));
		persistent.setPasswordRecoverKey(null);
		memberService.update(persistent);
		redirectionUrl = getRequest().getContextPath() + "/";
		addActionMessage("密码修改成功！");
		return SUCCESS;
	}

	public String addConsult() {
		String memberId = (String) getSession(Member.LOGIN_MEMBER_ID_SESSION_NAME);
		Member member = memberService.get(memberId);
		consult.setMember(member);
		consult.setReply(false);
		consult.setProduct(productService.get(id));
		productConsultService.save(consult);
		return ajaxJsonSuccessMessage("新增咨询成功");
	}

	@SuppressWarnings("unchecked")
	public String ajaxConsult() {
		if (pager == null) {
			pager = new Pager();
		}
		pager.setPageSize(ProductConsult.MAX_CONSULT_COUNT);
		
		String keyword = getRequest().getParameter("pager.keyword");
		String consultType = getRequest().getParameter("consultType");
		
		Product product = productService.get(id);
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(ProductConsult.class);
		detachedCriteria.add(Restrictions.eq("product", product));
		
		if(!StringUtil.isEmpty(keyword))
		{
			detachedCriteria.add(Restrictions.like("content","%"+keyword+"%"));
		}
		if(!StringUtil.isEmpty(consultType))
		{
			detachedCriteria.add(Restrictions.eq("type",Integer.parseInt(consultType)));
		}
		pager = productConsultService.findByPager(pager,detachedCriteria);
		return ajaxHtml(consultToHtml((List<ProductConsult>) pager
				.getList())+"#$#"+pager.getPageCount().toString());
	}

	@SuppressWarnings("unchecked")
	public String ajaxComment() {
		if (pager == null) {
			pager = new Pager();
		}
		pager.setPageSize(ProductComment.MAX_COMMENT_COUNT);
		String rank = getRequest().getParameter("rank");
		
		Product product = productService.get(id);
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(ProductComment.class);
		detachedCriteria.add(Restrictions.eq("product", product));
		
		if(!StringUtil.isEmpty(rank))
		{
			if(rank.contains("~"))
			{
				String[] ranks = rank.split("~");
				if(ranks.length==1)
				{
					detachedCriteria.add(Restrictions.ge("rank", Integer.parseInt(ranks[0])));
				}
				else
				{
					if(!StringUtil.isEmpty(ranks[0]))
					{
						detachedCriteria.add(Restrictions.ge("rank", Integer.parseInt(ranks[0])));
					}
					detachedCriteria.add(Restrictions.le("rank", Integer.parseInt(ranks[1])));
				}
			}
		}
		pager = productCommentService.findByPager(pager,detachedCriteria);
		
//		productCommentService.getProductCommentPager(product, pager);
		return ajaxHtml(commentToHtml((List<ProductComment>) pager
				.getList())+"#$#"+pager.getPageCount().toString());
	}
	
	

	// <div class="productComment">
	// <div class="left">
	// <img src="${base}${list.member.headIcon}" />
	// <p>${list.member.username}</p>
	// <p>${list.member.memberRank.name}</p>
	// <p>购买日期：${list.createDate}</p>
	// </div>
	// <div class="right">
	// <div class="title">${list.title}<span
	// class="createTime">${list.createDate}</span></div>
	// <ul>
	// <li>
	// <span class="lable">优点：</span>${list.advantage}
	// </li>
	// <li>
	// <span class="lable">不足：</span>${list.shortcoming}
	// </li>
	// <li>
	// <span class="lable">使用心得：</span>${list.experience}
	// </li>
	// </ul>
	// </div>
	// </div>
	// <div class="blank"></div>
	public String commentToHtml(List<ProductComment> list) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		StringBuffer sb = new StringBuffer();
		for (ProductComment productComment : list) {
			sb
					.append(String
							.format(
									"<div class=\"productComment\"><div class=\"left\"><img src=\"%s\" />"
											+ "<p>%s</p>"
											+ "<p>%s</p>"
											+ "<p>购买日期：%s</p></div><div class=\"right\">"
											+ "<div class=\"title\">%s"
											+ "<span class=\"createTime\">%s</span></div><ul><li>"
											+ "<span class=\"lable\">优点：</span>%s</li><li>"
											+ "<span class=\"lable\">不足：</span>%s</li><li>"
											+ "<span class=\"lable\">使用心得：</span>%s</li></ul></div></div><div class=\"blank\"></div>",
									"", productComment.getMember()
											.getUsername(), productComment
											.getMember().getMemberRank()
											.getName(), simpleDateFormat.format(productComment
											.getCreateDate()), productComment
											.getTitle(), simpleDateFormat.format(productComment
											.getCreateDate()), productComment
											.getAdvantage(), productComment
											.getShortcoming(), productComment
											.getExperience()));
		}
		return sb.toString();
	}

	// <div class="productConsult">
	// <div class="title">网友：%s&nbsp;&nbsp;普通会员</div>
	// <ul>
	// <li>
	// <span class="lable">咨询内容：</span><span class="content">d</span><span
	// class="time">2012-08-13</span>
	// </li>
	// <li>
	// <span class="lable">喜悦回复：</span><span
	// class="content">是放大师傅答复阿是肯定发剪短发发卡机发达发发的卡房间啊发放阿发开发及安防安抚安抚安抚安抚安抚发放沙发沙发沙发沙发</span><span
	// class="time">2012-08-13</span>
	// </li>
	// </ul>
	// </div>
	// <div class="blank"></div>
	public String consultToHtml(List<ProductConsult> list) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		StringBuffer sb = new StringBuffer();
		for (ProductConsult productConsult : list) {
			sb.append("<div class=\"productConsult\">");
			sb.append("<div class=\"title\">网友：");
			sb.append(productConsult.getMember().getUsername());
			sb.append("&nbsp;&nbsp;");
			sb.append(productConsult.getMember().getMemberRank().getName());
			sb.append("</div>");
			sb.append("<ul><li>");
			sb
					.append("<span class=\"lable\">咨询内容：</span><span class=\"content\">");
			sb.append(productConsult.getContent());
			sb.append("</span><span class=\"time\">");
			sb.append(simpleDateFormat.format(productConsult.getCreateDate()));
			sb
					.append("</span></li><li><span class=\"lable\">喜悦回复：</span><span class=\"content\">");
			sb.append(productConsult.getReply() ? productConsult
					.getReplycontent() : "尚未回复");
			sb.append("</span><span class=\"time\">");
			sb.append(productConsult.getReply()?simpleDateFormat.format(productConsult.getModifyDate()):"");
			sb.append("</span>");
			sb.append("</li></ul></div><div class=\"blank\"></div>");
		}
		return sb.toString();
	}

	public Member getMember() {
		return member;
	}

	public void setMember(Member member) {
		this.member = member;
	}

	public Boolean getIsAgreeAgreement() {
		return isAgreeAgreement;
	}

	public void setIsAgreeAgreement(Boolean isAgreeAgreement) {
		this.isAgreeAgreement = isAgreeAgreement;
	}

	public String getPasswordRecoverKey() {
		return passwordRecoverKey;
	}

	public void setPasswordRecoverKey(String passwordRecoverKey) {
		this.passwordRecoverKey = passwordRecoverKey;
	}

	public ProductConsult getConsult() {
		return consult;
	}

	public void setConsult(ProductConsult consult) {
		this.consult = consult;
	}
	
	

}